package com.xxx.config.exception.support;

import com.xxx.config.exception.BaseException;
import com.xxx.config.exception.ErrorResponseStatusCode;
import com.xxx.config.exception.GenExceptCode;
import com.xxx.config.exception.SystemException;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * 默认异常解析
 *
 * @version 1.0
 * @since 1.0
 */
@Slf4j
public class DefaultExceptionMapperSupport implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception exception) {
        if (exception instanceof BaseException be) {
            int status = ErrorResponseStatusCode.SERVICE_ERROR;
            if (exception instanceof SystemException) {
                status = ErrorResponseStatusCode.SYSTEM_ERROR;
                log.error(be.getMessage(), exception);
            }
            return Response.ok(be.buildBody(), MediaType.APPLICATION_JSON).status(status).build();
        } else if (exception instanceof WebApplicationException) {
            int status = ((WebApplicationException) exception).getResponse().getStatus();
            HashMap<String, Object> map = new HashMap<>();
            if (exception instanceof ClientErrorException) {
                map.put("code", ((ClientErrorException) exception).getResponse().getStatus());
            } else {
                map.put("code", ((WebApplicationException) exception).getResponse().getStatus());
            }
            map.put("msg", exception.getMessage());
            log.error(exception.getMessage(), exception);
            return Response.ok(map, MediaType.APPLICATION_JSON).status(status).build();
        } else if (exception instanceof IllegalArgumentException) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", GenExceptCode.Request_Param.getCode());
            map.put("msg", exception.getMessage());
            log.error(exception.getMessage(), exception);
            return Response.ok(map, MediaType.APPLICATION_JSON).status(ErrorResponseStatusCode.SERVICE_ERROR).build();
        } else {
            log.error(exception.getMessage(), exception);
            return Response.ok(new SystemException().buildBody()).status(ErrorResponseStatusCode.SYSTEM_ERROR).build();
        }
    }

}